package cn.Liujialin.user.controller;

import cn.Liujialin.basic.util.AjaxResult;
import cn.Liujialin.basic.util.PageList;
import cn.Liujialin.cation.BusinessException;
import cn.Liujialin.user.domain.User;
import cn.Liujialin.user.dto.UserDto;
import cn.Liujialin.user.query.UserQuery;
import cn.Liujialin.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;

    @PutMapping
    public AjaxResult addOrUpdate(@RequestBody User user){
        try {
            if(user.getId() == null){
                userService.save(user);
            }else{
                userService.update(user);
            }
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.fail("操作失败！");
        }
    }


    //删除   delete
    @DeleteMapping("/{id}")//使用{} 占位  //http://localhost:8080/dept/1
    public AjaxResult deleteById(@PathVariable("id") Long id){
        // 高级技师玩法
        try {
            userService.del(id);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.fail("删除失败！");
        }
    }

    /**
     * 如果前端传递的是数组，后端可以使用List 或者 数组接收
     * @return
     */
    @PatchMapping
    public AjaxResult patchDelete(@RequestBody List<Long> ids){
        try {
            userService.patchDelete(ids);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.fail("删除失败！");
        }
    }

    //获取一条数据
    @GetMapping("/{id}")
    public User queryById(@PathVariable("id") Long id){
        return userService.findById(id);
    }

    //查询所有
    @GetMapping
    public List<User> queryAll(){
        return userService.findByAll();
    }

    //分页  + 高级查询  post
    @PostMapping
    public PageList<User> queryPage(@RequestBody UserQuery query){
        return userService.queryPage(query);
    }

    /*
    * 注册接口*/
    @PostMapping("/register/phone")
    public AjaxResult register(@RequestBody UserDto userDto){
        try {
            userService.register(userDto);
            return AjaxResult.me();
        } catch (BusinessException e) {
            e.printStackTrace();
            return AjaxResult.fail(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.fail("注册失败,你丫丫的！");
        }

    }

}
